createDownloadWindow = (downInfo)->
  w = 780
  h = 440
  left = (screen.width / 2) - (w / 2)
  top = (screen.height / 2) - (h / 2)
  chrome.windows.create(
    {
      url: chrome.runtime.getURL("pages/down.html")
      type: "popup"
      height: h
      width: w
      left: left
      top: top
      focused: true
    }
    (window)->
#      code = "(" + ((downInfo)->
#        $(document).ready(->
#          addDownload(downInfo)
#          return
#        );
#        return true
#      ).toString() + ").call(this," + JSON.stringify(downInfo) + ");"
#      console.log(window.tabs)
      console.log(downInfo);
      setTimeout(
        ->
          chrome.runtime.sendMessage({
            type: "addDownload"
            val: downInfo
          })
        100
      )
#      chrome.tabs.executeScript(
#        window.tabs[0].id
#        {code: code}
#        (result)->
#          console.log("exe result : " + result)
#          console.log(chrome.runtime.lastError)
#      );
  );

onDownloadAdd = (downInfo, suggest)->
  if Utils.getSetting().downMode isnt "browser"
    chrome.downloads.cancel(
      downInfo.id
      ->
        Utils.fillCookies(downInfo, ->
          if Utils.getSetting().downMode is "ask"
            createDownloadWindow(downInfo)
          else
            Utils.directDownload(downInfo)
          return
        )
        return
    );
  suggest();
  return;

openYaaw = (server)->
  opts = Utils.getSetting()
  yaawURL = opts.yaawURL
  if yaawURL.lastIndexOf('/') is yaawURL.indexOf(':') + 2
    yaawURL = yaawURL + "/"
  onTab = (tab)->
    code = "(" + (
      (opts, server)->
        console.log("insert config.")
        window.localStorage.jsonrpc_history = JSON.stringify(s.url for s in opts.servers)
        if window.localStorage.jsonrpc_path isnt server
          window.localStorage.jsonrpc_path = server
          window.location.reload()
        return 1
    ).toString() + ")(#{JSON.stringify(opts)},'#{server.url}')"
    console.log("insert code #{code}")
    chrome.tabs.executeScript(
      tab.id
      {
        code: code
      }
      (result)->
        console.log("exec result #{result}")
        console.log(chrome.runtime)
        return
    )
    chrome.tabs.update(tab.id, {active: true})
    return

  chrome.tabs.query(
    {
      url: yaawURL
    }
    (tabs)->
      if tabs.length > 0
        onTab(tabs[0])
      else
        chrome.tabs.create(
          {
            url: yaawURL
          }
          onTab
        )
      return
  )
  return;

chrome.runtime.onMessage.addListener((msg)->

  if msg.type is "openYaaw"
    openYaaw(msg.val)

  if msg.type is "directDownload"
    setTimeout(
      ->
        Utils.directDownload(msg.val)
        return
      100
    )
    return
  return
)

chrome.downloads.onDeterminingFilename.addListener(onDownloadAdd);
console.log("loaded!")
if (chrome.downloads.setShelfEnabled)
  chrome.downloads.setShelfEnabled(false);